import type * as Football from "@/pages/xinhaozhi/apis/type"

interface ChartData {
  xData: string[]
  seriesData: Array<{ name: string; data: (number | null)[] }>
}

/** 保留4位小数 */
export function toFixedFour(value: number | undefined): number | null {
  if (value === undefined || value === null) return null
  return Number(value.toFixed(4))
}

/** 生成每小时一个null的时间序列 */
export function generateHourlyNullSeries(startTime: string, endTime: string): string[] {
  const start = new Date(startTime)
  const end = new Date(endTime)
  const timePoints: string[] = []
  
  // 从实际开始时间的整点开始
  let current = new Date(start)
  current.setMinutes(0, 0, 0) // 设置为整点
  
  // 确保实际开始时间也被包含在时间序列中
  const startTimeString = start.getFullYear() + '-' + 
    String(start.getMonth() + 1).padStart(2, '0') + '-' + 
    String(start.getDate()).padStart(2, '0') + ' ' + 
    String(start.getHours()).padStart(2, '0') + ':' + 
    String(start.getMinutes()).padStart(2, '0') + ':' + 
    String(start.getSeconds()).padStart(2, '0')
  
  // 总是先添加实际开始时间，确保包含最早的数据点
  timePoints.push(startTimeString)
  
  while (current <= end) {
    // 使用本地时间格式化，避免UTC转换
    const year = current.getFullYear()
    const month = String(current.getMonth() + 1).padStart(2, '0')
    const day = String(current.getDate()).padStart(2, '0')
    const hours = String(current.getHours()).padStart(2, '0')
    const minutes = String(current.getMinutes()).padStart(2, '0')
    const seconds = String(current.getSeconds()).padStart(2, '0')
    
    const timeString = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
    if (!timePoints.includes(timeString)) {
      timePoints.push(timeString)
    }
    current.setHours(current.getHours() + 1)
  }
  
  // 确保结束时间也被包含在时间序列中
  const endTimeString = end.getFullYear() + '-' + 
    String(end.getMonth() + 1).padStart(2, '0') + '-' + 
    String(end.getDate()).padStart(2, '0') + ' ' + 
    String(end.getHours()).padStart(2, '0') + ':' + 
    String(end.getMinutes()).padStart(2, '0') + ':' + 
    String(end.getSeconds()).padStart(2, '0')
  
  if (timePoints[timePoints.length - 1] !== endTimeString) {
    timePoints.push(endTimeString)
  }
  
  return timePoints
}

/** 合并真实数据到时间序列，并使用前值填充空值 */
export function mergeDataWithNullSeries(
  signals: Football.Signal[], 
  timePoints: string[], 
  dataField: 'signal_home' | 'signal_draw' | 'signal_away'
): (number | null)[] {
  if (signals.length === 0) return timePoints.map(() => null)
  
  // 按时间排序信号数据
  const sortedSignals = [...signals].sort((a, b) => {
    if (!a.odds_time || !b.odds_time) return 0
    return new Date(a.odds_time).getTime() - new Date(b.odds_time).getTime()
  })

  // 为每个时间点找到最近的前一个信号值
  const result: (number | null)[] = []
  let signalIndex = 0
  let lastValue: number | null = null

  timePoints.forEach(timePoint => {
    const currentTime = new Date(timePoint).getTime()
    
    // 找到当前时间点之前的最后一个信号
    while (signalIndex < sortedSignals.length && 
           sortedSignals[signalIndex].odds_time && 
           new Date(sortedSignals[signalIndex].odds_time).getTime() <= currentTime) {
      const value = toFixedFour(sortedSignals[signalIndex][dataField] as number | undefined)
      if (value !== null) {
        lastValue = value
      }
      signalIndex++
    }
    
    result.push(lastValue)
  })
  
  // 如果开头有空值，使用第一个有效值填充
  if (result.length > 0) {
    const firstValidValue = result.find(v => v !== null)
    if (firstValidValue !== null) {
      for (let i = 0; i < result.length; i++) {
        if (result[i] === null) {
          result[i] = firstValidValue
        } else {
          break
        }
      }
    }
  }
  
  return result
}

/** 使用前一个非空值填充数组中的空值 */
export function fillNullsWithPreviousValue(data: (number | null)[]): (number | null)[] {
  if (data.length === 0) return data
  
  const filledData = [...data]
  let lastValidValue: number | null = null
  
  // 正向遍历，使用前值填充
  for (let i = 0; i < filledData.length; i++) {
    if (filledData[i] !== null) {
      lastValidValue = filledData[i]
    } else if (lastValidValue !== null) {
      filledData[i] = lastValidValue
    }
  }
  
  // 如果开头有空值，反向遍历使用后值填充
  lastValidValue = null
  for (let i = filledData.length - 1; i >= 0; i--) {
    if (filledData[i] !== null) {
      lastValidValue = filledData[i]
    } else if (lastValidValue !== null) {
      filledData[i] = lastValidValue
    }
  }
  
  return filledData
}

/** 获取时间范围 */
export function getTimeRange(signals: Football.Signal[]): { start: string; end: string } | null {
  const validSignals = signals.filter(s => s.odds_time)
  if (validSignals.length === 0) return null
  
  // 直接使用时间字符串，避免时区转换
  const timeStrings = validSignals.map(s => s.odds_time!)
  const start = timeStrings.reduce((min, current) => current < min ? current : min)
  const end = timeStrings.reduce((max, current) => current > max ? current : max)
  
  return {
    start,
    end
  }
}

/** 为单个公司生成图表数据 */
export function generateCompanyChartData(signals: Football.Signal[], companyName: string): ChartData {
  if (!signals || signals.length === 0) {
    return { xData: [], seriesData: [] }
  }

  const timeRange = getTimeRange(signals)
  
  if (!timeRange) {
    return { xData: [], seriesData: [] }
  }

  // 生成每小时null的时间序列
  const timePoints = generateHourlyNullSeries(timeRange.start, timeRange.end)
  
  // 合并真实数据
  const homeData = mergeDataWithNullSeries(signals, timePoints, 'signal_home')
  const drawData = mergeDataWithNullSeries(signals, timePoints, 'signal_draw')
  const awayData = mergeDataWithNullSeries(signals, timePoints, 'signal_away')

  return {
    xData: timePoints,
    seriesData: [
      { name: `${companyName}-主队信号值`, data: homeData },
      { name: `${companyName}-平局信号值`, data: drawData },
      { name: `${companyName}-客队信号值`, data: awayData }
    ]
  }
}

export type { ChartData }
